﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Knife.Core.Util
{
    public class QuartzUtil
    {
        private IScheduler scheduler;
        private IScheduler GetScheduler()
        {
            var properties = new System.Collections.Specialized.NameValueCollection();
            //自定义Plugin 命名空间.类名,程序名称
            properties["quartz.plugin.MyPlugin.type"] = "Knife.Core.Model.CustomSchedulerPlugin,Knife.Core";
            if (null == scheduler)
            {
                var schedulerFactory = new StdSchedulerFactory(properties);
                scheduler = schedulerFactory.GetScheduler();
            }

            return scheduler;
        }
        public static ITrigger GetTrigger(string jobName, string jobGroup, int jobExecutePeroid,Knife.Core.Enums.JobTypeEnum.JobExecuteUnit jobExecuteUnit)
        {

            TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(jobName, jobGroup);
            if (jobExecutePeroid == 0)
            {
                TimeSpan span = new TimeSpan(0, 0, 0, 0, 1);
                builder.WithSimpleSchedule(t =>
                 t.RepeatForever().WithInterval(span));
            }
            else
            {
                switch (jobExecuteUnit)
                {
                    case Knife.Core.Enums.JobTypeEnum.JobExecuteUnit.Second:
                        builder.WithSimpleSchedule(t =>
                  t.RepeatForever().WithIntervalInHours(jobExecutePeroid));
                        break;
                    case Knife.Core.Enums.JobTypeEnum.JobExecuteUnit.Minute:
                        builder.WithSimpleSchedule(t =>
              t.RepeatForever().WithIntervalInMinutes(jobExecutePeroid));
                        break;
                    case Knife.Core.Enums.JobTypeEnum.JobExecuteUnit.Hour:
                        builder.WithSimpleSchedule(t =>
               t.RepeatForever().WithIntervalInSeconds(jobExecutePeroid));
                        break;

                }
            }
            ITrigger trigger = builder.Build();
            return trigger;
        }
        public static ITrigger GetTrigger(string jobName, string jobGroup,  string cornExplain)
        {

            TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(jobName, jobGroup);
            builder.WithCronSchedule(cornExplain);
            ITrigger trigger = builder.Build();
            return trigger;
        }
        /// <summary>
        /// 暂停job
        /// </summary>
        /// <param name="frame_task"></param>
        public void PauseJobTask(string jobName, string jobGroup)
        {
            IScheduler scheduler = GetScheduler();
            TriggerKey triggerkey = new TriggerKey(jobName, jobGroup);
            //暂停job
            scheduler.PauseJob(scheduler.GetTrigger(triggerkey).JobKey);
        }
        /// <summary>
        /// 重启job
        /// </summary>
        /// <param name="frame_task"></param>
        public void ResumeJobTask(string jobName, string jobGroup)
        {
            IScheduler scheduler = GetScheduler();
            TriggerKey triggerkey = new TriggerKey(jobName, jobGroup);
            //job
            scheduler.ResumeJob(scheduler.GetTrigger(triggerkey).JobKey);
        }
        /// <summary>
        /// 移除job
        /// </summary>
        /// <param name="frame_task"></param>
        public void RemoveTask(string jobName, string jobGroup)
        {
            IScheduler scheduler = GetScheduler();
            TriggerKey triggerkey = new TriggerKey(jobName, jobGroup);
            //停止job
            scheduler.ResumeJob(scheduler.GetTrigger(triggerkey).JobKey);
            //删除相关的job任务 
            scheduler.DeleteJob(scheduler.GetTrigger(triggerkey).JobKey);

        }
        /// <summary>
        /// 开启任务，包含开启暂停与重启与新增
        /// </summary>
        /// <param name="frame_task"></param>
        public void StartTaskWithCycle(string jobName, string jobGroup, string jobClassName, int jobExecutePeroid, Knife.Core.Enums.JobTypeEnum.JobExecuteUnit jobExecuteUnit)
        {
            IScheduler scheduler = GetScheduler();
            TriggerKey triggerkey = new TriggerKey(jobName, jobGroup);
            ITrigger trigger = scheduler.GetTrigger(triggerkey);
            if (null != trigger && scheduler.CheckExists(trigger.JobKey))
            {
                //如果有这个job，说明是暂停的任务，重启即可
                ResumeJobTask(jobName, jobGroup);
            }
            else
            {
                //没有这个job，说明是新增的，或者是停止后开启的
                JobDataMap jobData = new JobDataMap();
                jobData.Add("jobName", jobName);
                jobData.Add("jobGroup", jobGroup);
                IJobDetail job = JobBuilder.Create(Type.GetType(jobClassName)).SetJobData(jobData).Build();
                //如果是停止的job，先暂停trigger
                if (scheduler.CheckExists(triggerkey))
                {
                    scheduler.PauseTrigger(triggerkey);
                    scheduler.ScheduleJob(job, trigger);
                    //重启触发器  
                    scheduler.ResumeTrigger(triggerkey);
                }
                else
                {
                    //新增trigger
                    scheduler.PauseTrigger(triggerkey);
                    trigger = GetTrigger(jobName, jobGroup, jobExecutePeroid, jobExecuteUnit);
                    scheduler.ScheduleJob(job, trigger);
                }

            }
        }
        /// <summary>
        /// 开启任务，包含开启暂停与重启与新增
        /// </summary>
        /// <param name="frame_task"></param>
        public void StartTaskWithCorn(string jobName, string jobGroup, string jobClassName, string cornExplain)
        {
            IScheduler scheduler = GetScheduler();
            TriggerKey triggerkey = new TriggerKey(jobName, jobGroup);
            ITrigger trigger = scheduler.GetTrigger(triggerkey);
            if (null != trigger && scheduler.CheckExists(trigger.JobKey))
            {
                //如果有这个job，说明是暂停的任务，重启即可
                ResumeJobTask(jobName, jobGroup);
            }
            else
            {
                //没有这个job，说明是新增的，或者是停止后开启的
                JobDataMap jobData = new JobDataMap();
                jobData.Add("jobName", jobName);
                jobData.Add("jobGroup", jobGroup);
                IJobDetail job = JobBuilder.Create(Type.GetType(jobClassName)).SetJobData(jobData).Build();
                //如果是停止的job，先暂停trigger
                if (scheduler.CheckExists(triggerkey))
                {
                    scheduler.PauseTrigger(triggerkey);
                    scheduler.ScheduleJob(job, trigger);
                    //重启触发器  
                    scheduler.ResumeTrigger(triggerkey);
                }
                else
                {
                    //新增trigger
                    scheduler.PauseTrigger(triggerkey);
                    trigger = GetTrigger(jobName, jobGroup, cornExplain);
                    scheduler.ScheduleJob(job, trigger);
                }

            }
        }
        public void CloseScheduler()
        {
            IScheduler scheduler = GetScheduler();
            if (scheduler.IsStarted)
            {
                scheduler.PauseAll();
                scheduler.Clear();
                scheduler.Shutdown(true);
            }
        }
    }
}
